package cn.stylefeng.guns.sys.modular.system.quartz.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.BtyReemploy;
import cn.stylefeng.guns.sys.modular.system.entity.BtyWx;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyReemployParam;
import cn.stylefeng.guns.sys.modular.system.service.BtyReemployService;
import cn.stylefeng.guns.sys.modular.system.service.BtyWxService;
import cn.stylefeng.guns.sys.modular.system.service.WeChatSendTempMsgService;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 再次入职员工微信推送消息定时器
 *
 * @author: tianzhen
 * @date: 2022/5/6 16:57
 */
@Component
@Slf4j
public class ReemploySendMsgJob {

    @Resource
    private BtyReemployService reemployService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private BtyWxService btyWxService;


    /**
     * 每天上午9点公众号推送消息
     */
    @XxlJob("reemploySendMsgJob")
    public void reemploySendMsg() {
        //每天上午九点获取昨天再次入职员工数据
        try {
            log.info("-----------------再次入职员工微信推送消息定时器开始-----------------");
            List<BtyReemploy> reemployList = reemployService.reemployList(new BtyReemployParam());
            if(CollectionUtil.isNotEmpty(reemployList)){
                List<String> sendIds = new ArrayList<>();
                //发送信息
                this.sendMsg(reemployList, sendIds);

                if(CollectionUtil.isNotEmpty(sendIds)){
                    //更新记录的发送状态
                    reemployService.updateSendStatusByIds(sendIds);
                }
            }
            log.info("-----------------再次入职员工微信推送消息定时器结束-----------------");
        } catch (Exception e) {
            log.info("再次入职员工微信推送消息失败：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 获取发送人的openid和组装发送内容
     *
     * @param: reemployList 再次入职员工信息
     * @param: sendIds      发送成功的标识
     * @return:
     */
    private void sendMsg(List<BtyReemploy> reemployList, List<String> sendIds)throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //给关注用户推送消息
        List<String> openidList = reemployService.getOpenidList();
        //获取手机对应openid的关系
        List<BtyWx> wxList = btyWxService.getUserOpenid();
        Map<String, String> wxMap = wxList.stream().collect(Collectors.toMap(BtyWx::getPhone, BtyWx::getOpenid, (o, n) -> n));
        //暂存接收人的openid
        List<String> openids = new ArrayList<>(3);
        for(BtyReemploy info : reemployList){
            //获取运营经理和督导的微信openid
            this.getSendMsgOpenid(info.getOperationsManagerInfo(), info.getSupervisionInfo(), wxMap, openids);
            openids.addAll(openidList);

            StringBuffer strBuf = new StringBuffer();
            if(info.getEntryDate() == null || info.getOriginalEntryDate() == null){
                //入职日期和原来入职日期为空；不发送消息
                continue;
            }
            //【半天妖xxx店】王刚，身份证：370181111111111111，入职日期2022-3-29，曾经在【半天妖万达店】入职，原入职日期2022-1-10
            strBuf.append("【").append(info.getEntryStore()).append("】").append(info.getReempName()).append("，身份证：").append(info.getIdentifyCard()).append("，入职日期")
                    .append(sdf.format(info.getEntryDate())).append("，曾经在【").append(info.getOriginalEntryStore()).append("】入职，原入职日期").append(sdf.format(info.getOriginalEntryDate()));
            if(info.getLeaveDate() != null){
                strBuf.append("，离职日期").append(sdf.format(info.getLeaveDate()));
            }
            String[] strArr = {"消息通知", "再次入职人员信息", DateUtil.getNow(), strBuf.toString()};
            //设置参数格式
            JSONObject msgParam = weChatSendTempMsgService.setTempParam("再次入职人员", "", strArr);
            if(CollectionUtil.isNotEmpty(openids)){
                if(weChatSendTempMsgService.sendMessage(openids, msgParam)){
                    sendIds.add(info.getId());
                }
            }
            openids.clear();
        }
    }

    /**
     * 获取运营经理和督导的openid
     *
     * @param:  operationsManagerInfo  运营经理信息
     * @param:  supervisionInfo        督导信息
     * @param:  wxMap                  手机号和openid对应关系
     * @param:  openids                暂存openid
     * @return:
     */
    private void getSendMsgOpenid(String operationsManagerInfo, String supervisionInfo, Map<String, String> wxMap, List<String> openids){
        //获取运营经理和督导的微信openid
        if(StringUtils.isNotBlank(operationsManagerInfo)){
            String phone = operationsManagerInfo.split("/")[1];
            if(wxMap.containsKey(phone)){
                openids.add(wxMap.get(phone));
            }
        }
        if(StringUtils.isNotBlank(supervisionInfo)){
            String phone = supervisionInfo.split("/")[1];
            if(wxMap.containsKey(phone)){
                openids.add(wxMap.get(phone));
            }
        }
    }

}